import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/login/index.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('../views/register/index.vue'),
      meta: { title: '注册' }
    },
    {
      path: '/forgot-password',
      name: 'ForgotPassword',
      component: () => import('../views/forgot-password/index.vue'),
      meta: { title: '找回密码' }
    },
    {
      path: '/',
      component: () => import('../layout/index.vue'),
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('../views/dashboard/index.vue'),
          meta: { title: '仪表板' }
        },
        {
          path: 'users',
          name: 'Users',
          component: () => import('../views/users/index.vue'),
          meta: { title: '用户管理' }
        },
        {
          path: 'roles',
          name: 'Roles',
          component: () => import('../views/roles/index.vue'),
          meta: { title: '角色管理' }
        },
        {
          path: 'departments',
          name: 'Departments',
          component: () => import('../views/departments/index.vue'),
          meta: { title: '部门管理' }
        },
        {
          path: 'profile',
          name: 'Profile',
          component: () => import('../views/profile/index.vue'),
          meta: { title: '个人资料' }
        },
        {
          path: 'permissions',
          name: 'Permissions',
          component: () => import('../views/permissions/index.vue'),
          meta: { title: '权限管理' }
        }
      ]
    }
  ]
})

// Navigation guard
router.beforeEach((to, from, next) => {
  console.log('路由守卫: 从', from.path, '到', to.path)

  // Set page title
  document.title = to.meta.title ? `${to.meta.title} - 后台管理系统` : '后台管理系统'

  // Check if the route requires authentication
  const isAuthenticated = localStorage.getItem('token')
  console.log('路由守卫: 是否已认证:', !!isAuthenticated)

  // 不需要认证的页面
  const publicPages = ['/login', '/register', '/forgot-password']

  if (!publicPages.includes(to.path) && !isAuthenticated) {
    console.log('路由守卫: 需要认证但未登录，重定向到登录页')
    next('/login')
  } else if (publicPages.includes(to.path) && isAuthenticated) {
    console.log('路由守卫: 已登录但访问登录页，重定向到仪表板')
    next('/dashboard')
  } else {
    console.log('路由守卫: 正常导航')
    next()
  }
})

export default router
